#include "EventProcessor.h"
#include "EventProcessorImp.h"
#include "Errors.h"
#include "Swap.h"

EventProcessor::EventProcessor(void){
  // we just make the pointer null to make sure
  // none of the functions have any effect
  evProc = NULL;
  numCopies = new DistributedCounter(1);
  noDelete = false;
}

EventProcessor::EventProcessor(EventProcessorImp* obj){
  evProc = obj;
  numCopies = new DistributedCounter(1);
  noDelete=true;
}

void EventProcessor::ProcessMessage(Message& msg){
  if (evProc!=NULL){
    evProc->ProcessMessage(msg);
  } else {
    WARNING("Message sent to an unititialized EventProcessor");
  }
}

bool EventProcessor::ForkAndSpin(int node){
  if (evProc!=NULL)
    return evProc->ForkAndSpin(node);
  else
    return false;
}

void EventProcessor::WaitForProcessorDeath(void){
  if (evProc!=NULL)
    evProc->WaitForProcessorDeath();
  // otherwise we just return since there is nothing to wait for    
}

EventProcessor::~EventProcessor(){
  // is this the last copy?
  if (numCopies->Decrement(1)==0){
    // distroy the event processor and the counter
    if (evProc!=NULL && !noDelete)
      delete evProc;
    
    delete numCopies;
  }
}

void EventProcessor::Swap(EventProcessor& other){
  SWAP(evProc, other.evProc);
  SWAP(numCopies, other.numCopies);
  SWAP(noDelete, other.noDelete);
}

void EventProcessor::CopyFrom(EventProcessor& other){
  // same code as the destructor
  if (numCopies->Decrement(1)==0){
    // distroy the event processor and the counter
    if (evProc!=NULL && !noDelete)
      delete evProc;
    
    delete numCopies;
  }
  
  // put in the new content
  evProc=other.evProc;
  numCopies=other.numCopies;
  noDelete=other.noDelete;
  numCopies->Increment(1);
}

  
